package cbfg.butil

import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.annotation.StringRes

/**
 * 添加人：  Tom Hawk
 * 添加时间：2019/10/23 13:05
 * 功能描述：
 * <p>
 * 修改人：  Tom Hawk
 * 修改时间：2019/10/23 13:05
 * 修改内容：
 */
object ToastUtils {
    private val toast: Toast by lazy {
        Toast.makeText(AppHolder.app, "", Toast.LENGTH_SHORT)
    }

    fun showShort(@StringRes msgRes: Int) {
        showShort(AppHolder.app.getString(msgRes))
    }

    fun showShort(msg: String) {
        show(msg, Toast.LENGTH_SHORT)
    }

    fun showLong(@StringRes msgRes: Int) {
        showLong(AppHolder.app.getString(msgRes))
    }

    fun showLong(msg: String) {
        show(msg, Toast.LENGTH_LONG)
    }

    fun debugShowShort(msg: String) {
        debugShow(msg, Toast.LENGTH_SHORT)
    }

    fun debugShowLong(msg: String) {
        debugShow(msg, Toast.LENGTH_LONG)
    }

    private fun debugShow(msg: String, duration: Int) {
        if (isDebuggable) {
            show(msg, duration)
        }
    }

    private fun show(msg: String, duration: Int) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                toast.setText(msg)
                toast.duration = duration
                toast.show()
            } else {
                //如果不是主线程的话要切换到主线程:
                Handler(Looper.getMainLooper()).post {
                    toast.setText(msg)
                    toast.duration = duration
                    toast.show()
                }
            }
        } catch (_: Exception) {
        }
    }
}